package com.wss.code.rest;


import com.wss.common.model.Result;
import com.wss.service.fegin.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("code")
public class CodeController {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate ;


    @Autowired
    private EmailService emailService;

    @GetMapping("sendEmailCode")
    public Result sendEmailCode(@RequestParam("email")String email){
        String code = getCode(6);
        redisTemplate.opsForValue().set("code:"+email,code,5, TimeUnit.MINUTES);
        emailService.sendEmail(email,code);
        return  Result.success();
    }

    @GetMapping("validate")
    public Result validate(@RequestParam("email")String email,@RequestParam("code")String code){
        Object codeRedis = redisTemplate.opsForValue().get("code:" + email);
        if(null==codeRedis)
            return Result.fail("验证码过期，请重新获取！");
        if(!codeRedis.toString().equals(code))
            return Result.fail("验证码不对，请重新输入！");
        return  Result.success();
    }



    public  String getCode(int CODE_LEN){
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
        String captcha = ""; // 存放生成的验证码
        Random random = new Random();
        for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
            int index = random.nextInt(codeChar.length);
            captcha += codeChar[index];
        }
        return  captcha;
    }
}
